﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using HtmlAgilityPack;
using System.Text.RegularExpressions;

namespace planerka.Common
{
    public class tools
    {
        // сгененировать строку пароля
        public static string generatePasswordString()
        { 
            Random rng = new Random();
            int length = 4;// rng.Next(5, 7);
            char[] buf = new char[length];

            buf[0] = (char)('A' + rng.Next(26));

            for (int i = 4; i < 7; i++)
                buf[i] = (char)('a' + rng.Next(26));

            for (int i = 1; i < 4; i++)
                buf[i] = (char)('0' + rng.Next(9)); 

             return new string(buf);
        }

        // получить строку из DateTime?
        public static string getStringFromNullableDateTime(DateTime? _value)
        {
            return _value != null ? ((DateTime)_value).ToShortDateString() :"";
        }

        // получить конец дня для датыВремя
        public static DateTime getDayEndForDateTime(DateTime _value)
        {
            return _value.Date.AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);
        }

        // получить список из enum
        public static IEnumerable<SelectListItem> getEnumSelectList<T>()
        {
            return (Enum.GetValues(typeof(T)).Cast<T>().Select(
                enu => new SelectListItem() { Text = enu.ToString(), Value = enu.GetHashCode().ToString() })).ToList();
        }

        // получить строку с разделителями из списка
        public static string getStringFromList(List<string> items, string delimiter)
        {
            string tempDelimiter = ""; string outputString = "";

            foreach (object _item in items)
            {
                outputString += (tempDelimiter + _item.ToString());
                tempDelimiter = delimiter;
            }

            return outputString;

        }


        // Удалить HTML тэги (должны быть парные)
        public static string removeHTMLTags(string inputText)
        {
            string content = inputText;

            // С помощью регулярного выражения удаляем все тэги
            content = System.Text.RegularExpressions.Regex.Replace(content, @"</?.+?>", "");

            return content;

        }

        // санитаризация (чистка) HTML
        public static string SanitizeHtml(string html, bool isMailMode = false)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);
            html = html ?? "";

            string[] elementWhitelist = {
                                            "a", "u", "b", "strong", "i", "br", "hr ", "br", "h1", "h2", "h3", "h4", "h5", "h6", "span",
                                            "div", "blockquote", "em", "sub", "sup", "s", "font", "ul", "li", "ol", "p", "#text",
                                            "table", "tbody", "tr", "td", "th", "dl", "dt", "dd",  "img" /* h-mmm */, "fieldset", "legend"
                                        };

            string[] attributeWhiteList = { "class", "style", "src", "href", "color", "size", "width", "cellspacing", "cellpadding", "border" };

            if (isMailMode)
            {
                elementWhitelist = new string[] {
                                            "#text", "a", "u", "b", "strong", "i", "hr ", "br", "span", "p"
                                        };

                attributeWhiteList = new string[] {"src", "href", "color" };
            }

            IList<HtmlNode> hnc = doc.DocumentNode.Descendants().ToList();



            //remove non-white list nodes
            for (int i = hnc.Count - 1; i >= 0; i--)
            {
                HtmlNode htmlNode = hnc[i];
                if (!elementWhitelist.Contains(htmlNode.Name.ToLower()))
                {
                    htmlNode.Remove();
                    continue;
                }

                for (int att = htmlNode.Attributes.Count - 1; att >= 0; att--)
                {
                    HtmlAttribute attribute = htmlNode.Attributes[att];
                    //remove any attribute that is not in the white list (such as event handlers)
                    if (!attributeWhiteList.Contains(attribute.Name.ToLower()))
                    {
                        attribute.Remove();
                    }

                    //strip any "style" attributes that contain the word "expression"
                    if (attribute.Value.ToLower().Contains("expression") && attribute.Name.ToLower() == "style")
                    {
                        attribute.Value = string.Empty;
                    }


                    if (attribute.Name.ToLower() == "src" || attribute.Name.ToLower() == "href")
                    {
                        //strip if the link starts with anything other than http (such as jscript, javascript, vbscript, mailto, ftp, etc...)
                        // или локальные ресурсы
                        if (!(attribute.Value.StartsWith("http")
                            || attribute.Value.StartsWith("/"))) attribute.Value = "#";
                    }
                }
            }
            return doc.DocumentNode.WriteTo();
        }

        // получить только цифры из строки
        public static string getOnlyNumbers(string inputString)
        {
            List<char> charList = inputString.ToCharArray().ToList();
            string outputString = "";
            foreach (var charP in charList)
            {
                if (charP == '1' ||
                    charP == '2' ||
                    charP == '3' ||
                    charP == '4' ||
                    charP == '5' ||
                    charP == '6' ||
                    charP == '7' ||
                    charP == '8' ||
                    charP == '9' ||
                    charP == '0') outputString += charP;
            }

            return outputString;
        }

       
    }
}
